package cn.zd.demo1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;
import java.util.Random;

import cn.zd.demo1.sql.UserDBHelper;
import cn.zd.demo1.sql.entity.TabUserInfo;
import cn.zd.demo1.util.StringUtil;
import cn.zd.demo1.util.ViewCheckUtil;

public class SQLiteActivity extends AppCompatActivity implements View.OnClickListener {

    EditText et_db;
    EditText et_username;
    EditText et_usernamenew;
    EditText et_trans_username;
    EditText et_trans_userage;
    CheckBox cb_trans_flag;
    Button btn_createdb;
    Button btn_dropdb;
    Button btn_insertuser;
    Button btn_queryuser;
    Button btn_queryalluser;
    Button btn_deluser;
    Button btn_delall;
    Button btn_updateuser;
    Button btn_updateuserall;
    Button btn_trans_test;
    Button btn_ver;
    TextView tv_dbpath;
    TextView tv_userinfo;
    TextView tv_ver;
    UserDBHelper helper;
    private SharedPreferences sharedPreferences;
    private int version;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sqlite);
        Toast.makeText(this,this.getClass().getName(),Toast.LENGTH_LONG).show();

        sharedPreferences = getSharedPreferences("demo1", Context.MODE_PRIVATE);
        version = sharedPreferences.getInt("version",1);

        et_db = findViewById(R.id.et_db);
        et_username = findViewById(R.id.et_username);
        et_usernamenew = findViewById(R.id.et_usernamenew);
        et_trans_username = findViewById(R.id.et_trans_username);
        et_trans_userage = findViewById(R.id.et_trans_userage);

        tv_dbpath = findViewById(R.id.tv_dbpath);
        tv_userinfo = findViewById(R.id.tv_userinfo);
        tv_ver = findViewById(R.id.tv_ver);
        tv_ver.setText("当前版本号："+version);

        btn_createdb = findViewById(R.id.btn_createdb);
        btn_dropdb = findViewById(R.id.btn_dropdb);
        btn_insertuser = findViewById(R.id.btn_insertuser);
        btn_queryuser = findViewById(R.id.btn_queryuser);
        btn_queryalluser = findViewById(R.id.btn_queryalluser);
        btn_updateuser = findViewById(R.id.btn_updateuser);
        btn_updateuserall = findViewById(R.id.btn_updateuserall);
        btn_deluser = findViewById(R.id.btn_deluser);
        btn_ver = findViewById(R.id.btn_ver);
        btn_delall = findViewById(R.id.btn_delall);
        btn_trans_test = findViewById(R.id.btn_trans_test);
        cb_trans_flag = findViewById(R.id.cb_trans_flag);

        btn_createdb.setOnClickListener(this);
        btn_dropdb.setOnClickListener(this);
        btn_insertuser.setOnClickListener(this);
        btn_queryuser.setOnClickListener(this);
        btn_updateuser.setOnClickListener(this);
        btn_updateuserall.setOnClickListener(this);
        btn_queryalluser.setOnClickListener(this);
        btn_deluser.setOnClickListener(this);
        btn_delall.setOnClickListener(this);
        btn_trans_test.setOnClickListener(this);
        btn_ver.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {


        if (v.getId() == R.id.btn_createdb) {
            if(!ViewCheckUtil.checkEditText(et_db)) {
                Toast.makeText(this,"请输入数据库名称！",Toast.LENGTH_SHORT).show();
                return;
            }
            String dbpath = getFilesDir() +"/"+ et_db.getText().toString() +".db";

            SQLiteDatabase db = openOrCreateDatabase(dbpath, Context.MODE_PRIVATE, null);
            tv_dbpath.setText(String.format("数据库文件路径：[%s] ，版本：[%s]",dbpath,db.getVersion()));
            Toast.makeText(this,String.format("数据库%s创建成功",dbpath),Toast.LENGTH_SHORT).show();

        } else if(v.getId() == R.id.btn_dropdb) {
            if(!ViewCheckUtil.checkEditText(et_db)) {
                Toast.makeText(this,"请输入数据库名称！",Toast.LENGTH_SHORT).show();
                return;
            }
            String dbpath = getFilesDir() +"/"+ et_db.getText().toString() +".db";
            boolean result = deleteDatabase(dbpath);
            tv_dbpath.setText(String.format("数据库文件路径：[%s] ",dbpath));
            Toast.makeText(this,String.format("数据库%s删除%s",dbpath,result),Toast.LENGTH_SHORT).show();
        }  else if(v.getId() == R.id.btn_insertuser) {
            if(!ViewCheckUtil.checkEditText(et_username)) {
                Toast.makeText(this,"请输入用户名",Toast.LENGTH_SHORT).show();
                et_username.requestFocus();
                return;
            }
            String userName = et_username.getText().toString();
            TabUserInfo userInfo = new TabUserInfo();
            userInfo.setUserAge(new Random().nextInt(100));
            userInfo.setUserName(userName);
            long res = helper.insert(userInfo);
            tv_userinfo.setText("插入数据\n"+userInfo.toString());
            Toast.makeText(this,"用户数据插入结果:"+res,Toast.LENGTH_SHORT).show();
        }  else if(v.getId() == R.id.btn_queryuser) {
            if(!ViewCheckUtil.checkEditText(et_username)) {
                Toast.makeText(this,"请输入用户名",Toast.LENGTH_SHORT).show();
                et_username.requestFocus();
                return;
            }
            String oldUserName = et_username.getText().toString();
            List<TabUserInfo> userInfos = helper.query(oldUserName);
            Toast.makeText(this,"查询所有用户数:"+userInfos.size(),Toast.LENGTH_SHORT).show();
            tv_userinfo.setText("查询指定用户名"+ oldUserName+"数据\n"+ StringUtil.listToString(userInfos));

        }   else if(v.getId() == R.id.btn_queryalluser) {
            List<TabUserInfo> userInfos = helper.queryAll();
            Toast.makeText(this,"查询所有用户数:"+userInfos.size(),Toast.LENGTH_SHORT).show();
            tv_userinfo.setText("查询所有数据\n"+StringUtil.listToString(userInfos));
        }  else if(v.getId() == R.id.btn_updateuser) {
            if(!ViewCheckUtil.checkEditText(et_username)) {
                Toast.makeText(this,"请输入用户名",Toast.LENGTH_SHORT).show();
                et_username.requestFocus();
                return;
            }
            if(!ViewCheckUtil.checkEditText(et_usernamenew)) {
                Toast.makeText(this,"请输入新用户名",Toast.LENGTH_SHORT).show();
                et_usernamenew.requestFocus();
                return;
            }
            String oldUserName = et_username.getText().toString();
            String newUserName = et_usernamenew.getText().toString();
            long res = helper.update(newUserName, oldUserName);
            Toast.makeText(this,"用户数据更新结果:"+res,Toast.LENGTH_SHORT).show();

        }  else if(v.getId() == R.id.btn_updateuserall) {
            if(!ViewCheckUtil.checkEditText(et_usernamenew)) {
                Toast.makeText(this,"请输入新用户名",Toast.LENGTH_SHORT).show();
                et_usernamenew.requestFocus();
                return;
            }
            String newUserName = et_usernamenew.getText().toString();
            long res = helper.updateAll(newUserName);
            Toast.makeText(this,"用户数据更新结果:"+res,Toast.LENGTH_SHORT).show();
        } else if(v.getId() == R.id.btn_deluser) {
            if(!ViewCheckUtil.checkEditText(et_username)) {
                Toast.makeText(this,"请输入用户名",Toast.LENGTH_SHORT).show();
                et_username.requestFocus();
                return;
            }
            String userName = et_username.getText().toString();
            long res = helper.deleteByName(userName);
            Toast.makeText(this,"用户数据删除结果:"+res,Toast.LENGTH_SHORT).show();
        } else if(v.getId() == R.id.btn_delall) {
            long res = helper.deleteAll();
            Toast.makeText(this,"所有用户数据删除结果:"+res,Toast.LENGTH_SHORT).show();
        } else if(v.getId() == R.id.btn_ver) {
            SharedPreferences.Editor edit = sharedPreferences.edit();
            version++;
            edit.putInt("version",version);
            edit.commit();
            tv_ver.setText("升级版本："+version);
            Toast.makeText(this,"版本+1，重新打开试试:",Toast.LENGTH_SHORT).show();
        }else if(v.getId() == R.id.btn_trans_test) {
            if(!ViewCheckUtil.checkEditText(et_trans_username)) {
                Toast.makeText(this,"请输入姓名",Toast.LENGTH_SHORT).show();
                et_trans_username.requestFocus();
                return;
            }
            if(!ViewCheckUtil.checkEditText(et_trans_userage)) {
                Toast.makeText(this,"请输入年纪",Toast.LENGTH_SHORT).show();
                et_trans_userage.requestFocus();
                return;
            }
            boolean rollback = cb_trans_flag.isChecked();
            TabUserInfo trans = new TabUserInfo();
            trans.setUserName(et_trans_username.getText().toString());
            trans.setUserAge(Integer.parseInt(et_trans_userage.getText().toString()));
            SQLiteDatabase db = helper.openWrite();
            try {
                db.beginTransaction();
                helper.insert(trans);
                if (rollback) {
                    Toast.makeText(this,"异常中断，两条数据都将不会保存",Toast.LENGTH_SHORT).show();
                    throw new RuntimeException("回滚异常测试！");
                }
                trans.setUserName(trans.getUserName()+"-copy");
                trans.setUserAge(trans.getUserAge()*2);
                helper.insert(trans);
                db.setTransactionSuccessful();
                Toast.makeText(this,"正常测试,两条数据都将保存",Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
              e.printStackTrace();
            } finally {
                db.endTransaction();
                btn_queryalluser.callOnClick();
            }
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        helper = UserDBHelper.getInstance(this, version);
        Toast.makeText(this,"数据库打开成功",Toast.LENGTH_SHORT).show();
        helper.openRead();
        helper.openWrite();
    }

    @Override
    protected void onStop() {
        super.onStop();
        helper.closeDb();
    }
}